package com.bond.jumber.server.netty;

import com.bond.jumper.common.decode.MessageToServerDecoder;
import com.bond.jumper.common.encode.MessageToClientEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;

@Component
public class NettyServerRunner implements CommandLineRunner {

    @Value("${netty.server.port}")
    private int port;

    @Value("${netty.server.websocket.path}")
    private String websocketPath;

    @Value("${netty.server.websocket.port}")
    private int websocketPort;

    @Override
    public void run(String... args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // 客户端-服务端
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new MessageToServerDecoder());
                            ch.pipeline().addLast(new MessageToClientEncoder());
                            ch.pipeline().addLast(new NettyServerHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            // 浏览器-服务端
            ServerBootstrap websocketBootstrap = new ServerBootstrap();
            websocketBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            // webSocket协议本身是基于http协议的，所以这边也要使用http编解码器
                            ch.pipeline().addLast(new HttpServerCodec());
                            // 大数据流支持
                            ch.pipeline().addLast(new ChunkedWriteHandler());
                            ch.pipeline().addLast(new HttpObjectAggregator(8192));
                            // 处理WebSocket升级握手、Ping、Pong等消息
                            ch.pipeline().addLast(new WebSocketServerProtocolHandler(websocketPath));
                            // 自定义的handler，处理业务逻辑
                            ch.pipeline().addLast(new WebSocketHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture futureServer = serverBootstrap.bind(port).sync();
            ChannelFuture futureWebsocket = websocketBootstrap.bind(websocketPort).sync();

            futureServer.channel().closeFuture().sync();
            futureWebsocket.channel().closeFuture().sync();

        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}